package com.dubito.tmdbmovie.ui.component

import android.app.Activity
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.paging.PagingData
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import coil.compose.AsyncImage
import com.dubito.tmdbmovie.R
import com.dubito.tmdbmovie.common.bounceClick
import com.dubito.tmdbmovie.common.items
import com.dubito.tmdbmovie.common.pagingLoadingState
import com.dubito.tmdbmovie.data.datasource.remote.ApiURL
import com.dubito.tmdbmovie.data.model.MovieItem
import com.dubito.tmdbmovie.ui.navigation.NavigationScreen
import com.dubito.tmdbmovie.ui.navigation.currentRoute
import com.dubito.tmdbmovie.ui.theme.cornerRadius10
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.material.fade
import com.google.accompanist.placeholder.material.placeholder
import com.google.accompanist.placeholder.material.shimmer
import kotlinx.coroutines.flow.Flow

@Composable
fun HomeScreen(
    navController: NavController,
    movies: Flow<PagingData<MovieItem>>,
    modifier: Modifier = Modifier
) {
    val activity = (LocalContext.current as? Activity)
    val progressBarFirstLoad = remember { mutableStateOf(false) }
    val progressBarAppend = remember { mutableStateOf(false) }
    val errorMsg = remember { mutableStateOf("") }
    val openDialog = remember { mutableStateOf(false) }
    val snackBarHostState = remember { SnackbarHostState() }
    val moviesItems: LazyPagingItems<MovieItem> = movies.collectAsLazyPagingItems()

    BackHandler(enabled = (currentRoute(navController) == NavigationScreen.HOME)) {
        // execute your custom logic here
        openDialog.value = true
    }
    Box(modifier = modifier) {
        Column {
            CircularIndeterminateProgressBar(isDisplayed = progressBarFirstLoad.value, 0.4f)
            LazyVerticalGrid(
                columns = GridCells.Fixed(2),
                modifier = Modifier.padding(start = 5.dp, top = 5.dp, end = 5.dp),
                content = {
                    items(moviesItems) { item ->
                        item?.let {
                            MovieItemView(item, navController)
                        }
                    }
                }
            )
        }
        if (progressBarAppend.value) {
            LinearProgressIndicator(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 5.dp)
                    .align(Alignment.BottomEnd)
            )
        }
        if (errorMsg.value.isNotBlank()) {
            Box(modifier = Modifier.fillMaxSize()) {
                Column(
                    modifier = Modifier.align(Alignment.Center),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(text = errorMsg.value)
                    Button(onClick = {
                        moviesItems.retry()
                    }) {
                        Text(text = stringResource(R.string.retry))
                    }
                }

//                scope.launch {
//                    snackBarHostState.showSnackbar("服务器连接失败....")
//                }
            }
        }
        if (openDialog.value) {
            ExitAlertDialog(navController, {
                openDialog.value = it
            }, {
                activity?.finish()
            })
        }
    }
    moviesItems.pagingLoadingState(
        isLoaded = { progressBarFirstLoad.value = it },
        isAppend = { progressBarAppend.value = it },
        errorMsg = { errorMsg.value = it ?: "" }
    )
}

@Composable
fun MovieItemView(item: MovieItem, navController: NavController) {
    var isSuccess by remember {
        mutableStateOf(false)
    }
    Column(modifier = Modifier.padding(5.dp)) {
        AsyncImage(
            model = ApiURL.IMAGE_URL.plus(item.posterPath),
            contentDescription = null,
            onSuccess = { isSuccess = true },
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .placeholder(visible = !isSuccess, highlight = PlaceholderHighlight.shimmer())
                .bounceClick()
                .size(250.dp)
                .cornerRadius10()
                .clickable {
                    // 点击跳转详情页
                    navController.navigate(NavigationScreen.MovieDetail.MOVIE_DETAIL.plus("/${item.id}"))
                }
        )
    }
}



